class WaterfallButton {
    constructor(prop) {
        this.el = prop.el
        this.texts = prop?.options?.texts || ['www.baidu.com', 'www.google.com', 'www.bing.com', 'www.sougou.com', 'www.so.com']
        this.colors = prop?.options?.colors || ['#f97a57', '#ca2a4e', '#f09cab', '#8f1a46', '#f7ddba']
        this.init()
    }
    init() {
        let box = document.createElement("div");
        box.className = "waterfall-box";
        for (let i = 0; i < this.colors.length; i++) {
            box.style.setProperty(`--color-${i}`, this.colors[i])
        }
        this.el.after(box)

        this.el.className = 'waterfall-button'
        box.appendChild(this.el)

        let bg = document.createElement("div");
        bg.className = "waterfall-bg"
        box.appendChild(bg)

        let width = Math.max(Math.floor(this.el.offsetWidth / this.texts.length), 18)

        for (let i = 0; i < this.texts.length; i++) {
            const text = this.texts[i];
            let pEl = document.createElement("p");
            pEl.className = "waterfall-text"
            pEl.style.width = `${width}px`
            pEl.style.left = `${i * width}px`
            bg.appendChild(pEl)

            let spans = this.randomSplitString(text)
            for (const span of spans) {
                let spanEl = document.createElement("span");
                spanEl.innerText = span
                spanEl.style.color = this.colors[Math.floor(Math.random() * this.colors.length)]
                pEl.appendChild(spanEl)
            }
            pEl.style.bottom = `${Math.floor(Math.random() * Math.floor(pEl.offsetHeight))}px`
        }
    }
    randomSplitString(str) {
        let result = []
        let minChars = Math.floor(str.length / 10)
        let maxChars = Math.floor(str.length / 3)
        while (str.length > 0) {
            let length = Math.floor(Math.random() * (maxChars - minChars + 1)) + minChars;
            let part = str.substring(0, length);
            str = str.substring(length);
            result.push(part);
        }
        return result;
    }
}